package com.theme.passport.controller.theme;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.theme.common.base.ConfigConstant;
import com.theme.common.mvc.exception.RRException;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.utils.UploadParams;
import com.theme.common.mvc.view.R;
import com.theme.passport.aspect.CurrentLimitRequest;
import com.theme.passport.controller.oss.cloud.OSSFactory;
import com.theme.passport.controller.sys.AbstractController;
import com.theme.passport.entity.SysRoleEntity;
import com.theme.passport.entity.SysUserEntity;
import com.theme.passport.entity.constant.*;
import com.theme.passport.entity.theme.ThemeAttachmentEntity;
import com.theme.passport.entity.theme.ThemeEntity;
import com.theme.passport.entity.theme.WidgeConfigEntity;
import com.theme.passport.entity.theme.WidgeEntity;
import com.theme.passport.service.SysRoleService;
import com.theme.passport.service.SysUserRoleService;
import com.theme.passport.service.SysUserService;
import com.theme.passport.service.theme.ThemeAttachmentService;
import com.theme.passport.service.theme.ThemeService;
import com.theme.passport.service.theme.WidgeConfigService;
import com.theme.passport.service.theme.WidgeService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tools.ant.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;


/**
 * 组件表
 *
 * @author live
 * @email 870459550@qq.com
 * @date 2022-06-21 10:01:48
 */
@RestController
@RequestMapping("widge/widge")
public class WidgeController extends AbstractController {
    @Autowired
    private WidgeService widgeService;

    @Autowired
    private ThemeService themeService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private WidgeConfigService widgeConfigService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private ThemeAttachmentService attachmentService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("widge:widge:list")
    public R list(@RequestParam Map<String, Object> params) {
        // 根据用户查询用户角色，如果是设计师就查询他的，不是则查询所有的
        SysUserEntity user = getUser();
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
        if (roleIdList != null && roleIdList.size() == 1) {
            Long userRoleId = roleIdList.get(0);
            List<SysRoleEntity> sysRoleList = sysRoleService.queryRoleListByName(SysRoleNameEnum.DESIGNER.getName());
            if (sysRoleList != null && sysRoleList.size() == 1) {
                SysRoleEntity sysRoleEntity = sysRoleList.get(0);
                if (sysRoleEntity.getRoleId().equals(userRoleId)) {
                    params.put("userId", user.getUserId() + "");
                }
            }
        }
        params.put("themeShow", true);
        PageUtils page = widgeService.queryPage(params);
        List<WidgeEntity> list = (List<WidgeEntity>) page.getList();
        list.forEach(theme -> {
            SysUserEntity byId = sysUserService.getById(theme.getUserId());
            theme.setUseNickname(byId.getNickname());
        });
        page.setList(list);
        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/distinctNameList")
    @RequiresPermissions("widge:widge:list")
    public R distinctNameList(@RequestParam Map<String, Object> params) {
        // 根据用户查询用户角色，如果是设计师就查询他的，不是则查询所有的
        SysUserEntity user = getUser();
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
        if (roleIdList != null && roleIdList.size() == 1) {
            Long userRoleId = roleIdList.get(0);
            List<SysRoleEntity> sysRoleList = sysRoleService.queryRoleListByName(SysRoleNameEnum.DESIGNER.getName());
            if (sysRoleList != null && sysRoleList.size() == 1) {
                SysRoleEntity sysRoleEntity = sysRoleList.get(0);
                if (sysRoleEntity.getRoleId().equals(userRoleId)) {
                    params.put("userId", user.getUserId() + "");
                }
            }
        }
        params.put("themeShow", true);
//        PageUtils page = widgeService.queryPageBydistinctName(params);
//        List<WidgeEntity> list = (List<WidgeEntity>) page.getList();
//        list.forEach(theme ->{
//            List<WidgeEntity> widgeEntities = widgeService.queryWidgeListByName(theme.getName());
//            WidgeEntity widge = widgeEntities.get(0);
//            SysUserEntity byId = sysUserService.getById(widge.getUserId());
//            widge.setUseNickname(byId.getNickname());
//            BeanUtils.copyProperties(widge,theme);
//        });

        String keyword = (String) params.get("key");
        String status = (String) params.get("status");
        String free = (String) params.get("free");
        String userId = (String) params.get("userId");
        String themeId = (String) params.get("themeId");
        String typeId = (String) params.get("typeId");
        String all = (String) params.get("all");
        String classifyId = (String) params.get("classifyId");

        IPage<WidgeEntity> iPage = new Page<>();
        iPage.setCurrent(new Long(params.get("page").toString()));
        iPage.setPages(new Long(params.get("limit").toString()));
        QueryWrapper queryWrapper =  new QueryWrapper<WidgeEntity>()
                .eq(StringUtils.isNotBlank(free), "free", free)
                .eq(StringUtils.isNotBlank(userId), "user_id", userId)
                .eq(StringUtils.isNotBlank(typeId), "type_id", typeId)
                .eq(StringUtils.isNotBlank(classifyId), "classify_id", classifyId)
                .eq(StringUtils.isNotBlank(themeId), "theme_id", themeId)
                .in(StringUtils.isNotBlank(status), "status", status)
                .like(StringUtils.isNotBlank(keyword), "name", keyword)
                .orderByDesc("updated");
        if(!StrUtil.isEmptyIfStr(all)){
            if(all.equals( "1")){
                queryWrapper.isNull("theme_id");
            }else{
                queryWrapper.isNotNull("theme_id");
            }
        }
        IPage<WidgeEntity> page = widgeService.page(iPage,queryWrapper );
        return R.ok().put("page", page);
    }

    /**
     * 根据名称查询列表
     */
    @RequestMapping("/queryWidgeListByName")
    @RequiresPermissions("widge:widge:list")
    public R queryWidgeListByName(@RequestParam("name") String name) {
        // 根据用户查询用户角色，如果是设计师就查询他的，不是则查询所有的
        SysUserEntity user = getUser();
        Long userId = null;
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
        if (roleIdList != null && roleIdList.size() == 1) {
            Long userRoleId = roleIdList.get(0);
            List<SysRoleEntity> sysRoleList = sysRoleService.queryRoleListByName(SysRoleNameEnum.DESIGNER.getName());
            if (sysRoleList != null && sysRoleList.size() == 1) {
                SysRoleEntity sysRoleEntity = sysRoleList.get(0);
                if (sysRoleEntity.getRoleId().equals(userRoleId)) {
                    userId = user.getUserId();
                }
            }
        }
        List<WidgeEntity> widgeList = widgeService.queryWidgeListByNameAndUserId(name, userId);
        widgeList.forEach(widge -> {
            SysUserEntity byId = sysUserService.getById(widge.getUserId());
            widge.setUseNickname(byId.getNickname());
        });
        return R.ok().put("widgeList", widgeList);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        WidgeEntity widge = widgeService.getById(id);
        //查询详情主题详情图附件
        QueryWrapper<ThemeAttachmentEntity> fileNameWrapper = new QueryWrapper<>();
        fileNameWrapper.and(wrapper -> wrapper
                .eq("type", ThemeAttchmentTypeEnum.WIDGE.getValue())
                .eq("object_id", widge.getId()));
        List<ThemeAttachmentEntity> attachmentList = attachmentService.list(fileNameWrapper);
        if (attachmentList != null && attachmentList.size() > 0) {
            List<String> imageList = new ArrayList<>();
            attachmentList.forEach(attachment -> {
                imageList.add(attachment.getFileUrl());
            });
            widge.setWeatherImages(imageList);
        }
        return R.ok().put("widge", widge);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("widge:widge:save")
    public R save(@RequestBody WidgeEntity widge) {
        widge.setCreated(new Date());
        widge.setUpdated(new Date());
        SysUserEntity user = getUser();
        widge.setUserId(user.getUserId());
        widge.setUseNickname(user.getNickname());
        //主题组件判断规则:主题下每个尺寸只能有2个
        if (widge.getThemeId() != null) {
            QueryWrapper<WidgeEntity> nameWrapper = new QueryWrapper<>();
            nameWrapper.and(wrapper -> wrapper
                    .eq("theme_id", widge.getThemeId())
                    .eq("widget_size", widge.getWidgetSize()));
            List<WidgeEntity> nameList = widgeService.list(nameWrapper);
            if (widge.getWidgetSize().equals(WidgeSizeEnum.SMALL.getValue())) {
                if (nameList != null && nameList.size() >= 4) {
                    return R.error("该主题组件下小尺寸的组件最多能添加四个,请更改组件尺寸或者检查是否规范添加!");
                }
            } else if (nameList != null && nameList.size() >= 2) {
                return R.error("该主题组件下相同尺寸的组件已有两个(相同尺寸只能有两个),请更改组件尺寸或者检查是否规范添加!");
            } else {

            }
        } else {
            //通用组件判断规则 每个尺寸只能有一个
            //1.判断组件名称是否已经存在
            String name = widge.getName();
            QueryWrapper<WidgeEntity> nameWrapper = new QueryWrapper<>();
            nameWrapper.and(wrapper -> wrapper
                    .eq("name", name)
                    .eq("widget_size", widge.getWidgetSize()));
            List<WidgeEntity> nameList = widgeService.list(nameWrapper);
            if (nameList != null && nameList.size() > 0) {
                return R.error("该组件名称下相同尺寸的组件已存在,请更改组件名称或者尺寸!");
            }
        }

        widge.setFree(widge.getFree());
        widge.setStatus(widge.getStatus());
        widgeService.save(widge);

        List<String> imageList = widge.getWeatherImages();
        if (null != imageList || imageList.size() > 0) {
            List<ThemeAttachmentEntity> listAttachment = new ArrayList<>();
            imageList = imageList.stream().distinct().collect(Collectors.toList());
            imageList.forEach(image -> {
                ThemeAttachmentEntity themeEntity = new ThemeAttachmentEntity();
                themeEntity.setObjectId(widge.getId());
                themeEntity.setFileUrl(image);
                themeEntity.setType(ThemeAttchmentTypeEnum.WIDGE.getValue());
                themeEntity.setCreated(new Date());
                listAttachment.add(themeEntity);
            });
            attachmentService.saveBatch(listAttachment);
        }

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("widge:widge:update")
    public R update(@RequestBody WidgeEntity widge) {
        widge.setNts(ThemeNtsEnum.YES.getValue());
        widge.setUpdated(new Date());
        widgeService.updateById(widge);


        List<String> imageList = widge.getWeatherImages();
        if (imageList != null && imageList.size() > 0) {

            //删除主题详情图附件
            attachmentService.remove(Wrappers.<ThemeAttachmentEntity>query().lambda()
                    .eq(ThemeAttachmentEntity::getType, ThemeAttchmentTypeEnum.WIDGE.getValue())
                    .eq(ThemeAttachmentEntity::getObjectId, widge.getId()));

            List<ThemeAttachmentEntity> listAttachment = new ArrayList<>();
            imageList = imageList.stream().distinct().collect(Collectors.toList());
            imageList.forEach(image -> {
                ThemeAttachmentEntity themeEntity = new ThemeAttachmentEntity();
                themeEntity.setObjectId(widge.getId());
                themeEntity.setFileUrl(image);
                themeEntity.setType(ThemeAttchmentTypeEnum.WIDGE.getValue());
                themeEntity.setCreated(new Date());
                listAttachment.add(themeEntity);
            });
            attachmentService.saveBatch(listAttachment);
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("widge:widge:delete")
    public R delete(@RequestBody Long[] ids) {
        widgeService.removeByIds(Arrays.asList(ids));
        List<Long> widgeIds = Arrays.asList(ids);
        if (widgeIds.size() > 0) {
            widgeIds.forEach(widgeId -> {
                widgeConfigService.remove(Wrappers.<WidgeConfigEntity>query().lambda().eq(WidgeConfigEntity::getWidgeId, widgeId));
            });
        }
        return R.ok();
    }

    @RequestMapping("/copyWidge")
    public R copyWidge(@RequestParam("id") Long id) {
        WidgeEntity widge =  widgeService.getById(id);
        List<WidgeConfigEntity> widgeConfigEntityList = widgeConfigService.queryWidgeConfigList(id);
        widge.setId(null);
        widge.setThemeId(null);
        widge.setThemeName(null);
        widge.setStatus(ThemeStatusEnum.SHELVES.getValue());
        widge.setCreated( new Date());
        widge.setUpdated(new Date());
        widgeService.save(widge);
        for(WidgeConfigEntity widgeConfigEntity : widgeConfigEntityList){
            widgeConfigEntity.setWidgeId(widge.getId());
            widgeConfigEntity.setId(null);
            widgeConfigService.save(widgeConfigEntity);
        }
        return R.ok();
    }

    /**
     * 拷贝当前组件到主题组件
     * @param id 组件id
     * @param themeId 主题id
     * @return
     */
    @RequestMapping("/copyCurrentWidgeToThemeWidge")
    public R copyCurrentWidgeToThemeWidge(@RequestParam("id") Long id,
                                          @RequestParam("themeId") Long themeId) {
        WidgeEntity widge =  widgeService.getById(id);
        List<WidgeConfigEntity> widgeConfigEntityList = widgeConfigService.queryWidgeConfigList(id);
        widge.setId(null);

        ThemeEntity theme = themeService.getById(themeId);
        widge.setThemeId(themeId);
        widge.setThemeName(theme.getName());
        widge.setStatus(ThemeStatusEnum.SHELVES.getValue());
        widge.setCreated( new Date());
        widge.setUpdated(new Date());
        widgeService.save(widge);
        for(WidgeConfigEntity widgeConfigEntity : widgeConfigEntityList){
            widgeConfigEntity.setWidgeId(widge.getId());
            widgeConfigEntity.setId(null);
            widgeConfigService.save(widgeConfigEntity);
        }
        return R.ok();
    }

    /**
     * 拷贝当前组件到通用组件
     * @param id 组件id
     * @return
     */
    @RequestMapping("/copyCurrentWidgeToCommonWidge")
    public R copyCurrentWidgeToThemeWidge(@RequestParam("id") Long id) {
        WidgeEntity widge =  widgeService.getById(id);
        List<WidgeConfigEntity> widgeConfigEntityList = widgeConfigService.queryWidgeConfigList(id);
        widge.setId(null);
        widge.setThemeId(null);
        widge.setThemeName(null);
        widge.setStatus(ThemeStatusEnum.SHELVES.getValue());
        widge.setCreated( new Date());
        widge.setUpdated(new Date());
        widgeService.save(widge);
        for(WidgeConfigEntity widgeConfigEntity : widgeConfigEntityList){
            widgeConfigEntity.setWidgeId(widge.getId());
            widgeConfigEntity.setId(null);
            widgeConfigService.save(widgeConfigEntity);
        }
        return R.ok();
    }

    @RequestMapping("/copyTemp")
    public R copyTemp(@RequestParam("id") Long id) {
        WidgeEntity widge =  widgeService.getById(id);
        List<WidgeConfigEntity> widgeConfigEntityList = widgeConfigService.queryWidgeConfigList(id);
        widge.setId(null);
        widge.setName(widge.getName()+ "--副本");
        widge.setThemeId(null);
        widge.setThemeName(null);
        widge.setStatus(2);
        widge.setCreated( new Date());
        widge.setUpdated(new Date());
        widgeService.save(widge);
        for(WidgeConfigEntity widgeConfigEntity : widgeConfigEntityList){
            widgeConfigEntity.setWidgeId(widge.getId());
            widgeConfigEntity.setId(null);
            widgeConfigService.save(widgeConfigEntity);
        }
        return R.ok();
    }

    /**
     * 上传图片文件
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String fileExpandName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        if (!ConfigConstant.filePattern.matcher(fileExpandName.toUpperCase()).find()) {
            return R.error("文件格式不支持");
        }

        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = OSSFactory.build(null).uploadSuffix(file.getBytes(), suffix);

        return R.ok().put("filePath", url);
    }

    /**
     * 上传图片文件
     */

    @PostMapping("/uploadFileToDir")
    @CurrentLimitRequest(count = 100)
    public R uploadFileToDir(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        String fileExpandName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        if (!ConfigConstant.filePattern.matcher(fileExpandName.toUpperCase()).find()) {
            return R.error("文件格式不支持");
        }

        // 目录文件名称先设置为空
        String sourceDir = "widge" + "/" + DateUtils.format(new Date(), "yyyyMM") + random4();
        String filename = originalFilename.substring(0, originalFilename.indexOf("."));
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        UploadParams uploadParam = new UploadParams();
        uploadParam.setFileName(filename);
        uploadParam.setSourceDir(sourceDir);

        String url = OSSFactory.build(uploadParam).uploadSuffix(file.getBytes(), suffix);

        System.out.println(url);
        return R.ok().put("filePath", url);
    }

    private static String random4() {
        return String.valueOf(ThreadLocalRandom.current().nextInt(1000, 10000));
    }

}
